from django import forms
from io import BytesIO
from django.shortcuts import render, redirect, HttpResponse
from manage_worker import models
from manage_worker.utills.bootsrtap import BootStrapForm
from manage_worker.utills.encrypt import md5
from manage_worker.utills.code import check_code


# 继承BootStrapForm类中封装了bootstrap的样式，并且BootStrapForm已经继承了forms.Form
class LoginForm(BootStrapForm):
    # 此处使用form，应登录功能不需要与数据库做交互，只需要对数据库字段进行匹配就好
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True),  # render_value=True输入错了不删除密码
        required=True
    )
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput,  # render_value=True输入错了不删除密码
        required=True
    )

    def clean_password(self):
        '''
        密码字段的钩子函数，cleaned_data是前端通过post接口传入的数据，是一个字典
        :return:返回加密后的密码
        '''
        pwd = self.cleaned_data['password']
        return md5(pwd)


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    form = LoginForm(data=request.POST)
    if form.is_valid():

        # 验证验证码
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('img_code', '')
        if user_input_code.upper() != code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})

        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        # request.session把session存入后台，
        request.session['info'] = {'id': admin_object.id, 'name': admin_object.username}
        # 七日免登录
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/admin/list/')

    return render(request, 'login.html', {'form': form})


def image_code(request):
    img, code_str = check_code()

    # 把这个图片验证码存到session中
    request.session['img_code'] = code_str
    # 设置超时时间为60s
    request.session.set_expiry(60)

    # 在内存中创建一个对象
    stream = BytesIO()
    # 把文件存到内存中的对象
    img.save(stream, 'png')
    # stream.getvalue()获取对象
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.clear()
    return redirect('/login/')
